package com.ff.sca.suser.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ff.sca.common.entity.ztree.ZtreeNode;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.suser.dao.ScaPermissionDao;
import com.ff.sca.suser.entity.ScaPermission;
import com.ff.sca.suser.service.IScaPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * permission 权限表 服务实现类
 * </p>
 *
 * @author gw
 * @since 2018-09-20
 */
@Service
public class ScaPermissionServiceImpl extends ServiceImpl<ScaPermissionDao, ScaPermission> implements IScaPermissionService {

    @Autowired
    private ScaPermissionDao permissionDao;

    @Override
    public List<ZtreeNode> getPerminssionZtree(Integer pid) {
        if (CharUtil.isEmpty(pid)) {
            pid = 0;
        }
        List<ScaPermission> permisonList = permissionDao.getPerminssionZtree(pid);
        return createZtreeNode(permisonList);
    }

    private List<ZtreeNode> createZtreeNode(List<ScaPermission> permisonList) {
        List<ZtreeNode> nodes = new ArrayList<>();
        if (permisonList.size() > 0) {
            for (int i = 0; i < permisonList.size(); i++) {
                ScaPermission per = permisonList.get(i);
                ZtreeNode node = new ZtreeNode();
                node.setId(per.getId());
                node.setPid(per.getPid());
                node.setName(per.getName());
                node.setType(per.getType());
                // 2.动态加载子类，不查询出子类
                int childrenCount = permissionDao
                        .selectCount(new EntityWrapper<ScaPermission>().eq("pid", per.getId()));
                if (childrenCount > 0) {
                    node.setIsParent(true);
                }
                node.setChilCount(childrenCount);
                nodes.add(node);
            }
        }
        return nodes;
    }
}
